package com.zhanghe.study.io.old;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 转换流 InputStreamReader  OutputStreamWriter
 * 字节流->字符流
 * 字符流->字节流
 * 解码：字节数组->字符串
 * 编码：字符串->字节数组
 */
public class TestInputStreamReader {
    public static void main(String[] args) {
        copy("hello3.txt","hello5.txt");
    }

    /**
     * 复制文件
     * @param src
     * @param target
     */
    private static void copy(String src,String target){
        File srcFile = new File(src);
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader reader = null;

        File targetFile = new File(target);
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        BufferedWriter writer = null;
        try{
            // 解码
            fis = new FileInputStream(srcFile);
            isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
            reader = new BufferedReader(isr);

            // 编码
            fos = new FileOutputStream(targetFile);
            osw = new OutputStreamWriter(fos,StandardCharsets.UTF_8);
            writer = new BufferedWriter(osw);
            String str;
            while ((str = reader.readLine()) != null){
                writer.write(str);
                writer.newLine();
                writer.flush();
            }

        } catch (IOException e){
            e.printStackTrace();
        } finally {
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(isr != null){
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(osw != null){
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
